import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { CaptchaNotCorrectException } from '@/exceptions';
import { CaptchaService } from '@/common/captcha/captcha.service';

/**
 * 从 headers 中提取验证码并验证
 */
@Injectable()
export class CaptchaGuard implements CanActivate {
  constructor(private readonly captchaSercive: CaptchaService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const captchaRegExp = /^(?:key )([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})(?:; *value )([0-9a-z]{4})(?:;)?/i;
    const request = context.switchToHttp().getRequest();
    const captcha = request.headers.captcha;

    if (!captcha || !captchaRegExp.test(captcha)) {
      throw new CaptchaNotCorrectException();
    }
    const strs = captchaRegExp.exec(captcha);
    // const dto = new CaptchaChallengeDto(strs[1], strs[2]);

    const pass = await this.captchaSercive.validate(
      strs[1].toLowerCase(),
      strs[2],
    );
    if (!pass) {
      throw new CaptchaNotCorrectException();
    }
    return true;
  }
}
